package dao;

import model.User;
import utils.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserDao {
    public int addUser(User user) {
        try {
            String sql = "select * from user where username = ?";
            PreparedStatement ps = (PreparedStatement) DbUtil.con.prepareStatement(sql);
            ps.setString(1, user.getUserName());
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                System.out.println("该用户已存在");
                return 0;
            }
            sql = "insert into user(username,password,role,gender,phone) values(?,?,?,?,?)";
            PreparedStatement ps2 = (PreparedStatement) DbUtil.con.prepareStatement(sql);
            ps2.setString(1, user.getUserName());
            ps2.setString(2, user.getPassword());
            ps2.setInt(3, user.getRole());
            ps2.setString(4, user.getGender());
            ps2.setString(5, user.getPhone());
            return ps2.executeUpdate();
        } catch (Exception e) {
            System.out.println("UserDao.addUser错误");
        }
        return 0;
    }

    public User login(User user) {
        User resultUser = null;
        try {
            String sql = "select * from user where username = ? and password = ? and role = ?";
            PreparedStatement ps = (PreparedStatement) DbUtil.con.prepareStatement(sql);
            ps.setString(1, user.getUserName());
            ps.setString(2, user.getPassword());
            ps.setInt(3, user.getRole());
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {

                resultUser = new User();
                resultUser.setUserId(rs.getInt("id"));
                resultUser.setUserName(rs.getString("username"));
                resultUser.setGender(rs.getString("gender"));
                resultUser.setPhone(rs.getString("phone"));
                System.out.println(resultUser.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultUser;
    }

    public ResultSet list( int page, int limit) throws Exception {
        String sql = "select * from user";
        PreparedStatement ps = (PreparedStatement) DbUtil.con.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        return rs;
    }
}
